package com.sctvcloud.bazhong.ui.activities;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.canyinghao.canrefresh.other.CanRecyclerViewHeaderFooter;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.util.ViewUtils;
import com.ruihang.generalibrary.utils.DensityUtil;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.bazhong.R;
import com.sctvcloud.bazhong.application.Cache;
import com.sctvcloud.bazhong.base.BaseDetailActivity;
import com.sctvcloud.bazhong.application.Constances;
import com.sctvcloud.bazhong.beans.ADynamicsItem;
import com.sctvcloud.bazhong.beans.FComment;
import com.sctvcloud.bazhong.beans.SingleResult;
import com.sctvcloud.bazhong.http.AbsNetCallBack;
import com.sctvcloud.bazhong.http.NetUtils;
import com.sctvcloud.bazhong.http.ParamsEditor;
import com.sctvcloud.bazhong.ui.adapter.CommentDetailAdapter;
import com.sctvcloud.bazhong.ui.adapter.holder.AnchorCommentDynamicsHolder;
import com.sctvcloud.bazhong.ui.adapter.holder.AnchorHomeDynamicsHolder;
import com.sctvcloud.bazhong.ui.util.RBaseItemDecoration;
import com.sctvcloud.bazhong.ui.utils.SkipUtil;
import com.sctvcloud.bazhong.ui.utils.TitleUtils;
import com.sctvcloud.bazhong.utils.UserManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.sctvcloud.bazhong.ui.activities.MyAnchorDyActivity.INTO_ANCHORINFO_ISDIGG;

/**
 * 评论详情(主播圈的评论)
 */
public class CommentDetailActivity extends BaseDetailActivity implements CanRefreshLayout.OnRefreshListener
        , CanRecyclerViewHeaderFooter.OnLoadMoreListener {

    @BindView(R.id.comment_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView comment_list;
    @BindView(R.id.comment_footer)
    protected CanRecyclerViewHeaderFooter footer;
    @BindView(R.id.comment_foot_pb)
    protected ProgressBar pb;
    @BindView(R.id.comment_foot_loadmore)
    protected View allLoaded;
    @BindView(R.id.comment_foot_lay_normal)
    protected ViewGroup layFootNormal;
    @BindView(R.id.comment_foot_lay_empty)
    protected View layFootEmpty;
    private Handler handler;
    private LinearLayoutManager manager;

    private CommentDetailAdapter adapter;

    private ADynamicsItem dynamicsItem;

    //    private String id;
    private int capacity = 20;//请求数据条数
    private int indexNumber = 0;
    private int requestType = 3;// 1代表新闻评论  2专题评论 3主播评论
    private int commentType = 3;   //0新闻评论  1专题评论 2 直播评论

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        this.setTypeName(2);//日志统计 主播圈类型
        handler = new Handler();
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_comment_detail);
        butterUnbinder = ButterKnife.bind(this);
    }

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            footer.loadMoreComplete();
        } else {
            indexNumber += 20;
            getCommentNews(dynamicsItem.getDynamicId(), requestType, capacity, indexNumber);
        }
    }

    @Override
    public void onChildAttached(View v) {
        if (adapter.getItemCount() == 1 && v != null && layFootEmpty != null) {
//            JLog.e("bbvv  rfh=" + refreshLayout.getHeight() + "   vh=" + v.getHeight() + "  eh=" + layFootEmpty.getHeight());
            int h = refreshLayout.getHeight() - v.getHeight() - DensityUtil.dip2px(this, 30);
            if (h > layFootEmpty.getHeight()) {
                ViewGroup.LayoutParams lp = layFootEmpty.getLayoutParams();
                lp.height = h;
                layFootEmpty.setLayoutParams(lp);
            }
        }
    }

    @Override
    public void onRefresh() {
        capacity = 20;
        indexNumber = 0;
        getCommentNews(dynamicsItem.getDynamicId(), requestType, capacity, indexNumber);
    }

    /**
     * 获取全部数据
     *
     * @param ca
     */
    private void requestAll(int ca) {
        capacity = ca;
        indexNumber = 0;
        getCommentNews(dynamicsItem.getDynamicId(), requestType, capacity, indexNumber);
    }

    private void initView() {
        refreshLayout.setOnRefreshListener(this);
        manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        comment_list.setItemAnimator(new DefaultItemAnimator());
        comment_list.setLayoutManager(manager);
        comment_list.addItemDecoration(new RBaseItemDecoration(DensityUtil.dip2px(this, 1),
                ContextCompat.getColor(this, R.color.colorItemListDivider)));
//        boolean b=getIntent().hasExtra("id");
//        JLog.e("has id extra "+b);
//        id = getIntent().getStringExtra(EX_ID);
        Intent intent = getIntent();
        if (intent == null) {
            toast(R.string.data_wrong);
            finish();
            return;
        }
        dynamicsItem = (ADynamicsItem) intent.getSerializableExtra(EX_DATA);
        if (dynamicsItem == null || TextUtils.isEmpty(dynamicsItem.getAnchorId())) {
            toast(R.string.data_wrong);
            finish();
            return;
        }
        requestType = getIntent().getIntExtra(EX_TYPE_NEWS, 3);
        commentType = getIntent().getIntExtra(EX_COMMENT_TYPE, -1);

        footer.attachTo(comment_list, false);
        footer.setLoadMoreListener(this);
        footer.setVisibility(View.GONE);

        refreshLayout.autoRefresh();
//        refreshLayout.setRefreshEnabled(false);
//        ContentComment cc = dynamicsItem.getContentComment();
//        JLog.e("bbcc  cc="+cc);
//        initInfo(cc == null ? null : cc.getCommentList());
    }

    @OnClick(value = {R.id.comment_write_comment})
    public void commentClick(View view) {
        showCommentDialog(dynamicsItem.getDynamicId(), "", commentType);  //0代表新闻评论
    }

    @Override
    protected void onCommentGetListSuc(int count, List<FComment> fProgrammes) {
        super.onCommentGetListSuc(count, fProgrammes);
        if (indexNumber >= count || count < capacity) {
            footer.setLoadEnable(false);
            pb.setVisibility(View.GONE);
            allLoaded.setVisibility(View.VISIBLE);
            initInfo(fProgrammes);
        } else {
            requestAll(count);
//            if (!footer.isLoadEnable()) {
//                footer.setLoadEnable(true);
//                pb.setVisibility(View.VISIBLE);
//                allLoaded.setVisibility(View.VISIBLE);
//            }
        }


    }

    @Override
    protected void onCommentNetFinish(int mode, boolean isNetSuc) {
        if (mode == Constances.MODE_COMMENT_GET_NEW) {
            onNetFinish();
        }
        super.onCommentNetFinish(mode, isNetSuc);
    }

    @Override
    protected void onCommentSendSuc(int mode) {
        super.onCommentSendSuc(mode);
        onRefresh();
    }

    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        } else {
            footer.loadMoreComplete();
        }


    }

    /**
     * 处理评论数据
     *
     * @param datas
     * @return
     */
    private List<FComment> dataHandle(List<FComment> datas) {
        List<FComment> comments = new ArrayList<>();
        List<FComment> answers = new ArrayList<>();
        if (null != datas) {
            FComment comment;
            for (int i = 0; i < datas.size(); i++) {
                comment = datas.get(i);
                if (TextUtils.isEmpty(comment.getAnswerTo())) {
                    comments.add(comment);
                } else {
                    answers.add(comment);
                }
            }

            for (int j = 0; j < answers.size(); j++) {
                FComment co = answers.get(j);
                for (int k = 0; k < comments.size(); k++) {
                    if (!TextUtils.isEmpty(co.getAnswerToCommentId()) && co.getAnswerToCommentId().equalsIgnoreCase(comments.get(k).getCommentId())) {
                        comments.add(k + 1, co);
                        break;
                    }
                }
            }
        }
        return comments;

    }

    private void initInfo(List<FComment> datas) {
        List<FComment> list = dataHandle(datas);
        JLog.e("bbcc  datas=" + list);
        if (adapter == null) {
            adapter = new CommentDetailAdapter(this, null);
            dynamicsItem.setViewType(CommentDetailAdapter.TYPE_TOP);
            adapter.addData(dynamicsItem);
            adapter.addDatasEx(list);
            adapter.setPlayClick(new OnItemInternalClick() {
                @Override
                public void onItemInternalClick(View itemView, View view, int position) {

                }
            });
            adapter.setItemInternalClick(commentItemClick);
            adapter.setPlayClick(internalClick);
            adapter.setAnchorId(dynamicsItem.getUserId());
            comment_list.setAdapter(adapter);
        } else {
            if (indexNumber == 0) {
                adapter.removeFrom(1);
            }
            adapter.addDatasEx(list);
        }
        if (adapter.getItemCount() == 1) {
            ViewUtils.setViewVisible(layFootEmpty);
            ViewUtils.setViewGone(layFootNormal);
        } else {
            ViewUtils.setViewVisible(layFootNormal);
            ViewUtils.setViewGone(layFootEmpty);
        }
    }


    private OnItemInternalClick commentItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            FComment comment = (FComment) adapter.getItem(position);
            if (!TextUtils.isEmpty(comment.getCommentId())) {
                showCommentDialog(dynamicsItem.getDynamicId(), comment.getCommentId(), commentType);
            } else {
                toast("评论id为空");
            }
            //showCommentDialog(id, comment.getCommentId(), commentType);
        }
    };

    OnItemInternalClick internalClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            switch (view.getId()) {
                case R.id.tv_anchor_up:
                    if (!UserManager.isLoginS()) {
                        toLogin();
                        return;
                    }
                    ADynamicsItem dyUp = (ADynamicsItem) adapter.getItem(position);
//                if (dyUp.getAttitudesStatus()) {
//                    toast("已经点过赞啦");
//                    return;
//                }
                    doUp(dyUp, position);
                    break;

                case R.id.item_anchor_home_dynamics_video_play:
                    ADynamicsItem dynamics = (ADynamicsItem) adapter.getItem(position);
                    String contentVideoUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, dynamics.getContentVideo());
                    SkipUtil.skipToVideoPlay(CommentDetailActivity.this, contentVideoUrl, dynamics.getPlayedPos(), position);
                    break;
            }
        }
    };
    private AnchorCommentDynamicsHolder lastHolder = null;

    private void doUp(final ADynamicsItem aDynamicsItem, int position) {
        RecyclerView.LayoutManager manager = comment_list.getLayoutManager();
        View lastView = manager.findViewByPosition(position);
        if (null != lastView && comment_list.getChildViewHolder(lastView) instanceof AnchorCommentDynamicsHolder) {
            lastHolder = (AnchorCommentDynamicsHolder) comment_list.getChildViewHolder(lastView);
            if (null != lastHolder) {
                lastHolder.getTvUp().setDrawableEnlarge();
            }
        }
        ParamsEditor pe = new ParamsEditor();
        pe.put("dynamicId", aDynamicsItem.getDynamicId());
        pe.put("userId", UserManager.getInstance().getUser().getUserId());
        pe.put("fType", 1);//1 主播 2报料 3新闻(短视频) 4 直播
        NetUtils.getNetAdapter().doUpForDynamics(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onSuc(SingleResult singleResult) {
                if (singleResult.isSuccess()) {
                    SkipUtil.skipToAddUserOperate(CommentDetailActivity.this, getOwnerName(), 13, 2, "主播圈点赞", aDynamicsItem.getDynamicId(), Cache.getInstance().getCurrentChannelId());
                    dynamicsItem.setAttitudesCount(aDynamicsItem.getAttitudesStatus() ? aDynamicsItem.getAttitudesCount() - 1 : aDynamicsItem.getAttitudesCount() + 1);
                    dynamicsItem.setAttitudesStatus(!aDynamicsItem.getAttitudesStatus());
                    adapter.notifyDataSetChanged();
                    if (dynamicsItem.getAttitudesStatus()) {
                        addInvitation(Constances.ADD_INTEGRAL_DOUP, false);
                    }
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        Intent intent  = new Intent();
        intent.putExtra(INTO_ANCHORINFO_ISDIGG,dynamicsItem.getAttitudesStatus());
        setResult(RESULT_OK,intent);
        super.onBackPressed();
    }
}
